import requests
import logging
import json
from .lang import detect_language
from .config import Config

class Translator:
    def __init__(self):
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {
            "grant_type": "client_credentials",
            "client_id": Config.auth_api_key,
            "client_secret": Config.auth_secret_key,
        }
        self.token = str(requests.post(url, params=params).json().get("access_token"))
        self.logger = logging.getLogger()

    def _do_translate(self, text: str, from_lang: str = 'auto', to_lang: str = 'zh', terms: list[str] | None = None):
        url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + self.token
        payload = {
            "from": from_lang,
            "to": to_lang,
            "q": text,
        }
        if terms:
            payload["termIds"] = ','.join(terms)
        payload = json.dumps(payload)
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        }
        response = requests.request("POST", url, headers=headers, data=payload).json()
        if 'error_code' in response and response['error_code'] != 0:
            self.logger.error('API ERROR {}: {}'.format(response['error_code'], response['error_msg']))
        return response

    def translate(self, text: str, from_lang: str | None = None, to_lang: str | None = None, terms: list[str] | None = None):
        if from_lang is None:
            from_lang = detect_language(text)
        if to_lang is None:
            if from_lang == 'zh':
                to_lang = 'en'
            else:
                to_lang = 'zh'
        if to_lang == from_lang:
            return text
        if to_lang == from_lang:
            return text
        response = self._do_translate(text, from_lang, to_lang, terms)
        if 'result' not in response:
            return '|ERROR|'
        return '\n'.join(r['dst'] for r in response['result']['trans_result'])

    def chunked_translate(self, texts: list[str], from_lang: str = 'auto', to_lang: str = 'zh'):
        text = '\n'.join(t.replace('\n', ' ').replace('\r', ' ').replace('  ', ' ') for t in texts)
        response = self._do_translate(text, from_lang, to_lang)
        if 'result' not in response:
            return []
        return [(r['dst'], r['src']) for r in response['result']['trans_result']]

if __name__ == '__main__':
    t = Translator()
    print(t.translate('ビジュアルノベル制作チーム「超水道」でシナリオなど担当。\nたまに小説。お仕事はご連絡ください。'))
